package org.xiaoyu.rpc.protocol;

import cn.hutool.core.collection.ConcurrentHashSet;
import lombok.extern.slf4j.Slf4j;
import org.xiaoyu.rpc.Exporter;
import org.xiaoyu.rpc.Invoker;
import org.xiaoyu.rpc.RpcProtocolServer;
import org.xiaoyu.rpc.remoting.RemotingServer;

import java.lang.ref.WeakReference;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created By Have
 * 2021/7/12 21:04
 */
@Slf4j
public abstract class AbstractProtocol implements Protocol {

    protected final Map<String, Exporter<?>> exporterMap = new ConcurrentHashMap<>();
    protected final Set<WeakReference<Invoker<?>>> invokers = new ConcurrentHashSet<>();

    @Override
    public void destroy() {
        for (String key : exporterMap.keySet()) {
            Exporter<?> exporter = exporterMap.remove(key);
            try {
                if (exporter != null) {
                    if (log.isInfoEnabled()) {
                        log.info("Unexport service: " + exporter.getInvoker().getInterface().getName());
                    }
                    exporter.unexport();
                }
            } catch (Exception e) {
                log.warn(e.getMessage(), e);
            }
        }
    }
}


